<style lang="less">
#areaPolylineMap {
  width: 100%;
  height: 340px;
}
</style>
<template>
  <div style="background:#fff">
    <div class="search">
      <Row>
        <Col>
        <Card>
          <Row>
            <Form ref="searchForm"
                  :model="searchForm"
                  inline
                  :label-width="70"
                  class="search-form">
              <Form-item label="线路名称">
                <Input type="text"
                       v-model="searchForm.lineName"
                       :clearable="true"
                       placeholder="请输入线路名称"
                       style="width: 200px" />
              </Form-item>
              <Form-item style="margin-left:-35px;"
                         class="br">
                <Button @click="handleSearch"
                        type="primary"
                        icon="ios-search">搜索</Button>
                <Button @click="handleReset">重置</Button>
              </Form-item>
            </Form>
          </Row>
          <Row class="operation">
            <Button @click="add"
                    type="primary"
                    icon="md-add"
                    v-has="'add'">新增</Button>
            <circleLoading v-if="operationLoading" />
          </Row>
          <Row>
            <Alert show-icon>
              已选择
              <span class="select-count">{{selectCount}}</span> 项
              <a class="select-clear"
                 @click="clearSelectAll">清空</a>
            </Alert>
          </Row>
          <Row>
            <Table :loading="loading"
                   border
                   :columns="columns"
                   :data="data"
                   sortable="custom"
                   @on-sort-change="changeSort"
                   @on-selection-change="showSelect"
                   ref="table"></Table>
          </Row>
          <Row type="flex"
               justify="end"
               class="page">
            <Page :current="searchForm.current"
                  :total="total"
                  :page-size="searchForm.size"
                  @on-change="changePage"
                  @on-page-size-change="changePageSize"
                  :page-size-opts="[10,20,50,100]"
                  size="small"
                  show-total
                  show-elevator
                  show-sizer></Page>
          </Row>
        </Card>
        </Col>
      </Row>

    </div>
    <Modal :title="modalTitle"
           v-model="polylineModalVisible"
           :mask-closable="false"
           :width="1000"
           :styles="{top: '30px'}">
      <div id="areaPolylineMap"></div>
      <Tabs value="path">
        <TabPane label="线路信息"
                 tab="path"
                 name="path">
          <Form ref="polylineForm"
                :model="polylineForm"
                :label-width="110"
                :rules="polylineFormValidate"
                :disabled="modalType==1"
                style="padding-top:20px;">
            <Row>
              <Col :span="12">
              <FormItem label="线路名称"
                        prop="lineName">
                <Input v-model="polylineForm.lineName"
                       style="width:240px;" />
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem label="线路宽度(米)"
                        prop="width"
                        :rules=" {
                              required: true,
                              message: '限速为整数',
                              trigger: 'blur',
                              pattern: /^[0-9]\d*$/
                              }">
                <Input v-model="polylineForm.width"
                       style="width:240px;" />
              </FormItem>
              </Col>
            </Row>
            <Row>
              <Col :span="12">
              <FormItem label="坐标点"
                        prop="latlng">
                <Input v-model="polylineForm.latlng"
                       placeholder="在地图上绘制获得"
                       style="width:240px;"
                       :readonly="true" />
              </FormItem>
              </Col>
              <Col :span="12">
              <FormItem label="所属企业"
                        prop="companyId">
                <Select v-model="polylineForm.companyId"
                        style="width:240px;"
                        :clearable="true"
                        :transfer="true">

                  <Option v-for="item in companySelect"
                          :value="item.value"
                          :key="item.value">{{ item.label }}
                  </Option>
                </Select>
              </FormItem>
              </Col>
            </Row>

          </Form>
        </TabPane>
        <TabPane label="拐点信息"
                 tab="flexpoint"
                 name="flexpoint">
          <Table :loading="loading"
                 border
                 :columns="flexPointColumns"
                 :data="flexPointData"
                 ref="flexPointTable"></Table>
        </TabPane>
      </Tabs>

      <div slot="footer">
        <Button type="warning"
                icon="ios-brush"
                :loading="submitLoading"
                :disabled="modalType==1"
                @click="startDraw">开始绘制</Button>
        <Button type="primary"
                :loading="submitLoading"
                :disabled="modalType==1"
                @click="submitPolyline">提交</Button>
        <Button type="default"
                @click="polylineModalVisible = false">取消</Button>
      </div>
    </Modal>
    <Modal title="线路路段信息"
           v-model="flexPointModalVisible"
           :mask-closable="false"
           :width="800"
           :styles="{top: '100px'}">
      <Form ref="flexPointForm"
            :model="flexPointForm"
            :label-width="160"
            style="padding-top:20px;">
        <Row>
          <Col :span="12">
          <FormItem label="拐点名称"
                    prop="pointName"
                    :rules=" {
                              required: true,
                              message: '拐点名称必填',
                              trigger: 'blur',
                              type: 'string'
                              }">
            <Input v-model="flexPointForm.pointName"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
          <Col :span="12">

          </Col>
        </Row>
        <Row>
          <Col :span="12">
          <FormItem label="起点经度">
            <Input v-model="flexPointForm.lngStart"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
          <Col :span="12">
          <FormItem label="起点纬度">
            <Input v-model="flexPointForm.latStart"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
        </Row>
        <Row>
          <Col :span="12">
          <FormItem label="终点经度">
            <Input v-model="flexPointForm.lngEnd"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
          <Col :span="12">
          <FormItem label="终点纬度">
            <Input v-model="flexPointForm.latEnd"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
        </Row>
        <Row>
          <Col :span="12">
          <FormItem label="线路宽度(米)">
            <Input v-model="flexPointForm.width"
                   :readonly="true"
                   style="width:180px;" />
          </FormItem>
          </Col>
          <Col :span="12">

          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <!-- <Button type="primary"
                :loading="submitLoading"
                @click="submitFlexPoint">提交</Button> -->
        <Button type="default"
                @click="flexPointModalVisible = false">取消</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import AMap from 'AMap'
let mouseTool = null
import {
  getLinePageList,
  getCustomFlexPointPageList,
  editFlexPoint,
  addLine,
  editLine,
  deleteLine,
  getCompanySelect
} from '@/api/operate'
import circleLoading from '../../my-components/circle-loading.vue'
export default {
  name: 'polyline-manage',
  components: {
    circleLoading
  },
  data() {
    return {
      companySelect: [],
      loading: true,
      operationLoading: false,
      searchForm: {
        lineName: '',
        current: 1,
        size: 20,
        sort: 'createTime',
        order: 'desc'
      },
      polylinePoints: [],
      polylineModalVisible: false,
      modalType: 0,
      selectCount: 0,
      selectList: [],
      modalTitle: '',
      polylineForm: {
        customLineId: '',
        lineName: '',
        width: '',
        latlng: '',
        companyId: ''
      },
      polylineFormValidate: {
        lineName: [
          { required: true, message: '线路名称不能为空', trigger: 'blur' }
        ],
        latlng: [{ required: true, message: '请绘制线路', trigger: 'blur' }],
        companyId: [
          {
            required: true,
            message: '请选择企业',
            trigger: 'change',
            type: 'number'
          }
        ]
      },
      submitLoading: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '线路名称',
          key: 'lineName',
          width: 150,
          sortable: true
        },
        {
          title: '所属企业',
          key: 'companyName',
          minWidth: 240,
          sortable: true
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  directives: [
                    {
                      name: 'has',
                      value: 'edit'
                    }
                  ],
                  on: {
                    click: () => {
                      this.detail(params.row)
                    }
                  }
                },
                '查看'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  directives: [
                    {
                      name: 'has',
                      value: 'delete'
                    }
                  ],
                  on: {
                    click: () => {
                      this.remove(params.row)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      data: [],
      total: 0,
      flexPointColumns: [
        {
          title: '序号',
          type: 'index',
          width: 65,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '拐点名称',
          key: 'pointName',
          minWidth: 150
        },
        {
          title: '起点经度',
          key: 'lngStart',
          width: 160
        },
        {
          title: '起点纬度',
          key: 'latStart',
          width: 160
        },
        {
          title: '终点经度',
          key: 'lngEnd',
          width: 160
        },
        {
          title: '终点纬度',
          key: 'latEnd',
          width: 160
        },
        {
          title: '操作',
          key: 'action',
          width: 100,
          align: 'center',
          fixed: 'right',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'warning',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  directives: [
                    {
                      name: 'has',
                      value: 'linelist'
                    }
                  ],
                  on: {
                    click: () => {
                      this.editFlexPoint(params.row)
                    }
                  }
                },
                '查看'
              )
            ])
          }
        }
      ],
      flexPointData: [],
      flexPointForm: {},
      flexPointModalVisible: false,
      map: null
    }
  },
  methods: {
    init() {
      this.getLineList()
      this.mapInit()
      this.getCompanySelectList()
    },
    mapInit() {
      this.map = new AMap.Map('areaPolylineMap', {
        resizeEnable: true,
        zoom: 5,
        zooms: [3, 20],
        expandZoomRange: true,
        mapStyle: 'amap://styles/fresh'
      })
      let self = this
      this.map.plugin(['AMap.MapType'], function() {
        //地图类型切换
        var type = new AMap.MapType({
          defaultType: 0 //使用2D地图
        })
        self.map.addControl(type)
      })
      this.map.plugin(['AMap.ToolBar'], function() {
        //加载工具条
        var tool = new AMap.ToolBar()
        self.map.addControl(tool)
      })
      this.map.plugin(['AMap.MouseTool'], function() {
        //鼠标工具插件
        mouseTool = new AMap.MouseTool(self.map)
      })

      AMap.event.addListener(mouseTool, 'draw', function(event) {
        // event.obj 为绘制出来的覆盖物对象
        let drawObj = event.obj
        let points = drawObj.getPath()
        let newpoints = []
        self.polylinePoints = points
        points.forEach(item => {
          newpoints.push([item.lat, item.lng])
        })
        self.polylineForm.latlng = newpoints.join('|')

        mouseTool.close(false)
        self.$Message.info('绘制完成')
      })
    },
    getCompanySelectList() {
      getCompanySelect().then(res => {
        if (res.code == 0) {
          this.companySelect = res.data
        }
      })
    },
    startDraw() {
      this.map.clearMap()
      mouseTool.polyline({
        strokeColor: '#3366FF',
        strokeOpacity: 1,
        strokeWeight: 6,
        // 线样式还支持 'dashed'
        strokeStyle: 'solid'
        // strokeStyle是dashed时有效
        // strokeDasharray: [10, 5],
      })
      this.$Message.info('点击鼠标反键完成绘制')
    },
    changePage(v) {
      this.searchForm.current = v
      this.getLineList()
      this.clearSelectAll()
    },
    changePageSize(v) {
      this.searchForm.size = v
      this.getLineList()
    },
    getLineList() {
      // 多条件搜索
      this.loading = true
      getLinePageList(this.searchForm).then(res => {
        this.loading = false
        if (res.code == 0) {
          this.data = res.data.records
          this.total = res.data.total
        }
      })
    },
    getFlexPointList(customLineId) {
      this.loading = true
      getCustomFlexPointPageList({ customLineId: customLineId }).then(res => {
        this.loading = false
        if (res.code == 0) {
          this.flexPointData = res.data
        }
      })
    },
    handleSearch() {
      this.searchForm.current = 1
      this.searchForm.size = 20
      this.getLineList()
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.lineName = ''
      this.searchForm.current = 1
      this.searchForm.size = 20
      // 重新加载数据
      this.getLineList()
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false)
    },
    changeSort(e) {
      this.searchForm.sort = e.key
      this.searchForm.order = e.order
      if (e.order == 'normal') {
        this.searchForm.order = ''
      }
      this.getLineList()
    },
    submitPolyline() {
      this.$refs.polylineForm.validate(valid => {
        if (valid) {
          console.log(this)
          this.submitLoading = true
          let params = JSON.parse(JSON.stringify(this.polylineForm))
          let points = []
          let len = this.polylinePoints.length - 1
          for (let i = 0; i < len; i++) {
            let currPoint = this.polylinePoints[i]
            let nextPoint = this.polylinePoints[i + 1]
            points.push({
              pointName: '拐点' + (i + 1),
              width: params.width,
              latStart: currPoint.lat,
              lngStart: currPoint.lng,
              latEnd: nextPoint.lat,
              lngEnd: nextPoint.lng,
              ordering: i + 1
            })
          }
          params.points = points

          addLine(params).then(res => {
            this.submitLoading = false
            if (res.code == 0) {
              this.$Message.success('操作成功')
              this.getLineList()
              this.polylineModalVisible = false
            } else {
              this.$Message.error(res.msg)
            }
          })
        }
      })
    },
    add() {
      this.modalType = 0
      this.modalTitle = '新增线路'
      this.map.clearMap()
      this.polylineForm = {
        customLineId: '',
        lineName: '',
        width: '',
        latlng: '',
        companyId: ''
      }
      this.flexPointData = []
      this.polylineModalVisible = true
    },
    detail(v) {
      this.modalType = 1
      this.modalTitle = '查看线路'
      this.$refs.polylineForm.resetFields()
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = ''
        }
      }
      this.polylineForm = JSON.parse(JSON.stringify(v))
      this.getFlexPointList(this.polylineForm.customLineId)

      this.map.clearMap()

      // 构造矢量多边形
      let polyPoints = v.latlng.split('|')
      let path = []
      polyPoints.forEach(poly => {
        let item = poly.split(',')
        path.push(new AMap.LngLat(item[1], item[0]))
      })

      var polyline = new AMap.Polyline({
        path: path,
        strokeColor: '#3366FF',
        strokeOpacity: 1,
        strokeWeight: 6,
        // 线样式还支持 'dashed'
        strokeStyle: 'solid'
        // strokeStyle是dashed时有效
        // strokeDasharray: [10, 5],
      })

      this.map.add(polyline)
      this.map.setFitView()

      this.polylineModalVisible = true
    },
    remove(v) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除线路 ' + v.lineName + ' ?',
        loading: true,
        onOk: () => {
          deleteLine(v.customLineId).then(res => {
            this.$Modal.remove()
            if (res.code == 0) {
              this.$Message.success('删除成功')
              this.getLineList()
            } else {
              this.$Message.error(res.msg)
            }
          })
        }
      })
    },
    editFlexPoint(v) {
      this.flexPointModalVisible = true
      this.$refs.flexPointForm.resetFields()
      for (let attr in v) {
        if (v[attr] == null) {
          v[attr] = ''
        }
      }
      this.flexPointForm = JSON.parse(JSON.stringify(v))
    },
    submitFlexPoint() {
      this.$refs.flexPointForm.validate(valid => {
        if (valid) {
          this.submitLoading = true
          editFlexPoint(this.flexPointForm).then(res => {
            this.submitLoading = false
            if (res.code == 0) {
              this.$Message.success('操作成功')
              this.getFlexPointList(this.flexPointForm.customLineId)
              this.flexPointModalVisible = false
            } else {
              this.$Message.error(res.msg)
            }
          })
        }
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>